package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.po.Category;
import com.itheima.po.R;
import com.itheima.po.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @PostMapping("")
    public R<String> save(@RequestBody SetmealDto setmealDto){
        return R.success("添加成功");
    }
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(Integer page, Integer pageSize, String name){
//        从数据库中查询Page<Setmeal>然后根据setmeal的ID查询分类名字，
//        然后Page<SetmealDto>组装出来，返回给前端
//         返回的数据是SetmealDto 套餐数据与分类名字 组装成Page<SetmealDto>
//        1 从数据库中查询套餐中的数据Page<Setmeal>
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(name),Setmeal::getName,name);
//        倒序
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage,lambdaQueryWrapper);
//        2 根据Setmeal的id查询出分类的名字
        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(setmealDtoPage,setmealPage,"records");
        List<Setmeal> records = setmealPage.getRecords();
        //        3 组装SetmealDto返回给前端
        setmealDtoPage.setRecords(new ArrayList<>());
        for (Setmeal setmeal : records) {
            Category category = categoryService.getById(setmeal.getCategoryId());
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal,setmealDto);
            setmealDto.setCategoryName(category.getName());
            setmealDtoPage.getRecords().add(setmealDto);
        }
        return R.success(setmealDtoPage);
   }
//   步骤ids单个删除与批量删除
//    售卖中的套餐不能删除
//    如果要删除的套餐为停售状态，则删除套餐数据以及套餐菜品数据
    @DeleteMapping("")
    public R<String> delete(@RequestParam List<Long> ids){
        setmealService.deleteWithDish(ids);
        return R.success("删除成功");
    }
}
